import 'dart:async';
import 'dart:io';
import 'package:e_reception_flutter/common_widgets/common_confirm_cancel_dialog/common_confirm_cancel_dialog.dart';
import 'package:e_reception_flutter/common_widgets/common_pack_up_keyboard_widget/common_pack_up_keyboard_widget.dart';
import 'package:e_reception_flutter/constants/call_back.dart';
import 'package:e_reception_flutter/singleton/theme_repository/theme_repository.dart';
import 'package:e_reception_flutter/ui/new_terminal/bg_music/bean/bg_terminal_music_list_response_bean.dart';
import 'package:e_reception_flutter/ui/new_terminal/bg_music/bg_sys_recommend_music_view_model.dart';
import 'package:e_reception_flutter/ui/smart_home/publish/select_smart_home_bgm_event.dart';
import 'package:e_reception_flutter/ui/smart_home/publish/set_smart_home_folder_bgm_dialog.dart';
import 'package:e_reception_flutter/ui/smart_home/publish/show_progress_notifier.dart';
import 'package:e_reception_flutter/ui/smart_home/publish/smart_home_3d_link_demo_page.dart';
import 'package:e_reception_flutter/ui/smart_home/publish/smart_home_3d_upload_page.dart';
import 'package:e_reception_flutter/ui/smart_home/publish/smart_home_column_response_bean.dart';
import 'package:e_reception_flutter/ui/smart_home/publish/smart_home_publish_service.dart';
import 'package:e_reception_flutter/ui/smart_home/publish/smart_home_publish_set_image_cover_page.dart';
import 'package:e_reception_flutter/ui/smart_home/publish/smart_home_publish_set_video_cover_page.dart';
import 'package:e_reception_flutter/ui/smart_home/publish/smart_home_select_column_page.dart';
import 'package:e_reception_flutter/ui/smart_home/publish/smart_home_store_details_page.dart';
import 'package:e_reception_flutter/ui/smart_home/publish/video_upload_service.dart';
import 'package:e_reception_flutter/ui/smart_home/smart_home_view_model.dart';
import 'package:e_reception_flutter/utils/router_utils.dart';
import 'package:e_reception_flutter/utils/screen_utils.dart';
import 'package:e_reception_flutter/utils/vg_global_func.dart';
import 'package:e_reception_flutter/utils/vg_hud_utils.dart';
import 'package:e_reception_flutter/utils/vg_toast_utils.dart';
import 'package:e_reception_flutter/vg_widgets/light_annotated_region_style.dart';
import 'package:e_reception_flutter/vg_widgets/vg_image_widget/vg_cache_net_work_image.dart';
import 'package:e_reception_flutter/vg_widgets/vg_photo_preview/vg_photo_preview.dart';
import 'package:e_reception_flutter/vg_widgets/vg_text_field_widget/vg_text_field.dart';
import 'package:e_reception_flutter/vg_widgets/vg_top_bar_widget/vg_top_bar_widget.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:matisse_android_plugin/export_matisse.dart';
import 'package:path_provider/path_provider.dart';
import 'package:photo_preview/photo_preview_export.dart';
import 'package:vg_base/vg_arch_lib.dart';
import 'package:vg_base/vg_evnet_bus_lib.dart';
import 'package:vg_base/vg_permission_lib.dart';
import 'package:vg_base/vg_string_util_lib.dart';
import 'package:vg_flutter_base_moudle/vg_moudle_widget_lib.dart' as prefix;
import 'package:video_thumbnail/video_thumbnail.dart';
import '../../app_main.dart';
import '../smart_home_upload_service.dart';

/// 智能家居发布页面
class SmartHomePublishPage extends StatefulWidget {
  ///路由名称
  static const String ROUTER = "SmartHomePublishPage";

  final String shid;
  final String type;
  final List<ColumnListBean> columnList;
  final ColumnListBean currentColumn;

  //上传完成后回到的页面
  final String router;
  final String linkUrl;
  final String coverPath;
  final List<SmartHomeUploadItemBean> currentList;
  final String sfid;
  final String title;
  final String desc;
  final int coverIndex;
  final MusicListBean musicInfo;
  final List<MusicListBean> musicList;
  final bool isCreate;
  final VideoUploadService videoUploadService;

  const SmartHomePublishPage(
      {Key key,
        this.shid,
        this.type,
        this.columnList,
        this.currentColumn,
        this.router,
        this.linkUrl,
        this.coverPath,
        this.currentList,
        this.sfid,
        this.title,
        this.desc,
        this.coverIndex,
        this.musicInfo,
        this.musicList,
        this.isCreate,
        this.videoUploadService,
      })
      : super(key: key);

  @override
  _SmartHomePublishPageState createState() => _SmartHomePublishPageState();

  static Future<Map> navigatorPush(
      BuildContext context,
      String shid,
      String type,
      List<ColumnListBean> columnList,
      ColumnListBean currentColumn,
      {String router,
        String linkUrl,
        String coverPath,
        List<SmartHomeUploadItemBean> currentList,
        String sfid,
        String title,
        String desc,
        int coverIndex,
        MusicListBean musicInfo,
        List<MusicListBean> musicList,
        bool isCreate,
        VideoUploadService videoUploadService,
      }) {
    return RouterUtils.routeForFutureResult(
        context,
        SmartHomePublishPage(
          shid: shid,
          type: type,
          columnList: columnList,
          currentColumn: currentColumn,
          router: router,
          linkUrl: linkUrl,
          coverPath: coverPath,
          currentList: currentList,
          sfid: sfid,
          title: title,
          desc: desc,
          coverIndex: coverIndex,
          musicInfo: musicInfo,
          musicList: musicList,
          isCreate: isCreate,
          videoUploadService: videoUploadService,
        ),
        routeName: SmartHomePublishPage.ROUTER);
  }
}

class _SmartHomePublishPageState extends BaseState<SmartHomePublishPage> {
  TextEditingController _titleController;
  TextEditingController _desController;
  SmartHomeViewModel _viewModel;
  int _picCount = 0;

  //包含上传布局的默认数据
  List<SmartHomeUploadItemBean> _allList = List();

  //要上传的数据
  List<SmartHomeUploadItemBean> _uploadList = List();

  ///自定义默认上传布局，type为-1
  SmartHomeUploadItemBean _defaultItem =
  new SmartHomeUploadItemBean(type: "-1");

  List<ColumnListBean> _columnList;
  ColumnListBean _currentColumn = null;

  //封面图
  int _coverIndex;

  String _linkUrl;

  ScrollController _scrollController;

  MusicListBean _musicInfo;
  List<MusicListBean> _musicList = List();
  BgSysRecommendMusicViewModel _musicViewModel;
  StreamSubscription _selectBgmStreamSubscription;

  VideoPlayerController _videoHandleController;

  VideoUploadService _videoUploadService;
  @override
  void initState() {
    super.initState();
    _musicInfo = widget?.musicInfo;
    if(widget?.musicList != null){
      _musicList.addAll(widget?.musicList);
    }
    _videoUploadService = widget?.videoUploadService;
    _musicViewModel = new BgSysRecommendMusicViewModel(this, "");
    _scrollController = new ScrollController();
    _columnList = new List();
    if (widget?.columnList != null) {
      _columnList.addAll(widget?.columnList);
    }
    _currentColumn = widget?.currentColumn;
    _titleController = TextEditingController(text: widget?.title ?? "");
    _desController = TextEditingController(text: widget?.desc ?? "");
    _viewModel = SmartHomeViewModel(this);
    if ("03" == widget?.type) {
      if (widget?.currentList != null) {
        //编辑
        _uploadList.addAll(widget?.currentList);
        _allList.addAll(_uploadList);
        _coverIndex = 0;
        _linkUrl = _uploadList.elementAt(0).linkUrl;
      } else {
        _linkUrl = widget?.linkUrl??"";
        List<String> resultList = new List();
        resultList.add(widget?.coverPath);
        WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
          _doHandleData(resultList);
        });
      }
    } else {
      if (widget?.currentList != null && widget.currentList.isNotEmpty) {
        if (widget?.type == "01") {
          _coverIndex = widget?.coverIndex ?? 0;
        }
        _uploadList.addAll(widget?.currentList);
        if (_uploadList.length < 35) {
          _allList.clear();
          _allList.addAll(_uploadList);
          if (widget?.type == "01") {
            _allList.add(_defaultItem);
          }
        } else {
          _allList.clear();
          _allList.addAll(_uploadList);
        }
        WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
          if (widget?.type == "01") {
            Future.delayed(Duration(milliseconds: 100), () {
              _scrollController.jumpTo(_scrollController?.position?.maxScrollExtent);
            });
          }
        });
      } else {
        _allList.add(_defaultItem);
      }
    }
    _picCount = _uploadList.length;
    _selectBgmStreamSubscription =
        VgEventBus.global.on<SelectSmartHomeBgmEvent>()?.listen((event) {
          if(event.musicListBean == null && event.cancelUse){
            setState(() {
              _musicInfo = null;
            });
          }
        });
  }

  @override
  void dispose() {
    _titleController?.clear();
    _titleController?.dispose();
    _desController?.clear();
    _desController?.dispose();
    _selectBgmStreamSubscription?.cancel();
    _videoHandleController?.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return LightAnnotatedRegion(
        child: WillPopScope(
          onWillPop: _withdrawFront,
          child: Scaffold(
            resizeToAvoidBottomInset: false,
            resizeToAvoidBottomPadding: false,
            backgroundColor: Colors.white,
            body: _toMainColumnWidget(),
          ),
        ));
  }

  Widget _toMainColumnWidget() {
    return CommonPackUpKeyboardWidget(
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          _toTopBarWidget(),
          // _toSelectColumnWidget(),
          // Container(
          //   height: 10,
          //   color: Color(0XFFF6F7F9),
          // ),
          _toSmartHomeTitleWidget(),
          Container(
            margin: EdgeInsets.only(left: 15),
            height: 1,
            color: Color(0XFFEEEEEE),
          ),
          // _toUploadView(),
          _toDesWidget(),
          _toDesTextLengthWidget(),
          SizedBox(height: 4,),
          _toSelectImageWidget(),
          _toSelectBgmWidget(),
        ],
      ),
    );
  }

  // Widget _toUploadView(){
  //   if (_videoUploadService == null || _videoUploadService.getUploadingList() == null
  //       || _videoUploadService.getUploadingList().isEmpty) {
  //     return Container();
  //   }
  //   return Container(
  //     child: Consumer(
  //       builder: (context, ShowProgressNotifier notifier, child){
  //         _videoUploadService?.showProgressNotifier = notifier;
  //         return Text("正在上传视频:" + (notifier?.progress??0).toString(),
  //             style: TextStyle(color: Color(0xFF999999), fontSize: 13));
  //       },
  //     ),
  //   );
  // }

  ///页面标题
  Widget _toTopBarWidget() {
    String title = "共选择${_picCount ?? 0}图";
    if ("02" == widget?.type) {
      title = "视频";
    } else if ("03" == widget?.type) {
      title = "3D全景效果图";
    }

    return VgTopBarWidget(
      isShowBack: true,
      title: title,
      backgroundColor: Color(0XFFF6F7F9),
      titleColor: ThemeRepository.getInstance().getCardBgColor_21263C(),
      rightWidget: _toSaveWidget(),
      navFunction: (){
        onBackPressed();
      },
    );
  }

  void onBackPressed()async{
    if(_uploadList.length < 1 && StringUtils.isEmpty(_getTitle()) && StringUtils.isEmpty(_getDesc())){
      //直接返回
      RouterUtils.pop(context);
      return;
    }
    FocusScope.of(context).requestFocus(FocusNode());
    bool result =
    await CommonConfirmCancelDialog.navigatorPushDialog(context,
      title: "提示",
      content: "退出后将不会保存您的内容，确认退出？",
      cancelText: "取消",
      confirmText: "退出",
      confirmBgColor: ThemeRepository.getInstance().getPrimaryColor_1890FF(),
      cancelBgColor: Color(0xFFF6F7F9),
      titleColor: ThemeRepository.getInstance().getCardBgColor_21263C(),
      contentColor: ThemeRepository.getInstance().getCardBgColor_21263C(),
      widgetBgColor: Colors.white,
    );
    //去裁剪
    if(result??false){
      RouterUtils.pop(context);
    }
    return;
  }

  Future<bool> _withdrawFront() async {
    if(_uploadList.length < 1 && StringUtils.isEmpty(_getTitle()) && StringUtils.isEmpty(_getDesc())){
      //直接返回
      return true;
    }
    FocusScope.of(context).requestFocus(FocusNode());
    bool result =
    await CommonConfirmCancelDialog.navigatorPushDialog(context,
      title: "提示",
      content: "退出后将不会保存您的内容，确认退出？",
      cancelText: "取消",
      confirmText: "退出",
      confirmBgColor: ThemeRepository.getInstance().getPrimaryColor_1890FF(),
      cancelBgColor: Color(0xFFF6F7F9),
      titleColor: ThemeRepository.getInstance().getCardBgColor_21263C(),
      contentColor: ThemeRepository.getInstance().getCardBgColor_21263C(),
      widgetBgColor: Colors.white,
    );
    if(result??false){
      return true;
    }
    return false;
  }

  Widget _toSaveWidget() {
    return GestureDetector(
      behavior: HitTestBehavior.opaque,
      onTap: () {
        if(StringUtils.isEmpty(_getTitle()) && StringUtils.isEmpty(_getDesc())){
          VgToastUtils.toast(context, "请输入标题或描述");
          return;
        }
        if(_uploadList.length < 1){
          return;
        }
        _upload();
      },
      child: Container(
        width: 48,
        height: 24,
        decoration: BoxDecoration(
          color: (_uploadList.length > 0 && (StringUtils.isNotEmpty(_getTitle()) || StringUtils.isNotEmpty(_getDesc())))?ThemeRepository.getInstance().getPrimaryColor_1890FF():Color(0xFFCFD4DB),
          borderRadius: BorderRadius.circular(12),
        ),
        alignment: Alignment.center,
        child: Text(
          "发布",
          style: TextStyle(
              color: Colors.white, fontSize: 12, fontWeight: FontWeight.w500),
        ),
      ),
    );
  }

  void _upload() {
    // if(_uploadList?.length == 1 && StringUtils.isNotEmpty(_uploadList[0]?.netUrl) && PhotoPreviewToolUtils.isNetUrl(_uploadList[0]?.netUrl)){
    //   //编辑图片，无需上传
    //   SmartHomeUploadItemBean itemBean = _uploadList[0];
    //   _viewModel.editImage(context, widget?.shid, itemBean?.picid, itemBean?.backup, itemBean?.stid, itemBean?.style, widget?.router);
    //   return;
    // }

    if(widget?.type == "02" && StringUtils.isEmpty(_uploadList[0].netUrl)){
      _videoUploadService.upload(_uploadList[0], "", widget?.sfid ?? "", widget?.shid,
          _getDesc(), _coverIndex ?? 0, _getTitle(), _musicInfo?.id??"", widget?.type??"");
      VgToastUtils.toast(context, "已发送");
      RouterUtils.popUntil(
          context, widget?.router ?? SmartHomeStoreDetailsPage.ROUTER);
      return;
    }

    SmartHomePublishService service = SmartHomePublishService().setList(
      context,
      widget?.shid,
      // _currentColumn?.getScid(),
      "",
      _getTitle(),
      _getDesc(),
      _uploadList,
      _coverIndex ?? 0,
      widget?.sfid ?? "",
      _musicInfo?.id??"",
      type:widget?.type??"",
    );
    if (service != null) {
      VgHudUtils.show(context, "正在发布");
      if ((_uploadList?.length ?? 0) > 0) {
        //多图上传
        service.multiUpload(VgBaseCallback(onSuccess: (val) {
          VgHudUtils.hide(context);
          VgToastUtils.toast(AppMain.context, "上传完成");
          RouterUtils.popUntil(
              context, widget?.router ?? SmartHomeStoreDetailsPage.ROUTER);
        }, onError: (msg) {
          VgHudUtils.hide(context);
          VgToastUtils.toast(AppMain.context, "上传失败");
          RouterUtils.popUntil(
              context, widget?.router ?? SmartHomeStoreDetailsPage.ROUTER);
        }));
      }
    }
  }

  String _getDesc(){
    String desc = _desController.text.trim();
    if(desc.length > 200){
      desc = desc.substring(0, 200);
    }
    return desc;
  }

  String _getTitle(){
    String title = _titleController.text.trim();
    if(title.length > 30){
      title = title.substring(0, 30);
    }
    return title;
  }

  ///选择栏目布局
  Widget _toSelectColumnWidget() {
    return GestureDetector(
      behavior: HitTestBehavior.opaque,
      onTap: () async {
        ColumnListBean selectColumn =
        await SmartHomeSelectColumnPage.navigatorPush(
            context, _columnList, _currentColumn);
        if (selectColumn != null) {
          setState(() {
            _currentColumn = selectColumn;
          });
        }
      },
      child: Container(
        height: 50,
        alignment: Alignment.center,
        color: Colors.white,
        padding: EdgeInsets.symmetric(horizontal: 15),
        child: Row(
          children: [
            Text(
              "选择栏目：",
              style: TextStyle(
                fontSize: 14,
                color: ThemeRepository.getInstance().getCardBgColor_21263C(),
              ),
            ),
            Text(
              _currentColumn?.name ?? "",
              style: TextStyle(
                fontSize: 14,
                color: Color(0XFF1890FF),
              ),
            ),
            Spacer(),
            SizedBox(
              width: 9,
            ),
            Image.asset(
              "images/icon_arrow_right_grey.png",
              width: 6,
              color: Color(0XFF8B93A5),
            ),
          ],
        ),
      ),
    );
  }

  ///标题
  Widget _toSmartHomeTitleWidget() {
    Color color = Color(0XFFB0B3BF);
    if((_titleController?.text?.length??0) > 0){
      if((_titleController?.text?.length??0) <= 30){
        color = ThemeRepository.getInstance().getPrimaryColor_1890FF();
      }else{
        color = Color(0XFFF95355);
      }
    }
    return Container(
      color: Colors.white,
      alignment: Alignment.centerLeft,
      padding: EdgeInsets.only(left: 15, right: 10),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.center,
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Expanded(
            child: Container(
              constraints: BoxConstraints(
                  minHeight: 50,
                  maxHeight: 100
              ),
              child: VgTextField(
                controller: _titleController,
                keyboardType: TextInputType.text,
                autofocus: (widget?.isCreate??true),
                textAlign: TextAlign.left,
                style: TextStyle(
                    color: ThemeRepository.getInstance().getCardBgColor_21263C(),
                    fontWeight: FontWeight.w600,
                    fontSize: 14),
                decoration: new InputDecoration(
                    counterText: "",
                    hintText: "写个标题，便于管理，也能提高用户点击率～",
                    border: InputBorder.none,
                    hintStyle: TextStyle(fontSize: 14, fontWeight: FontWeight.w600, color: Color(0XFFB0B3BF))),
                maxLines: 2,
                minLines: 1,
                maxLimitLength: Platform.isAndroid ? 30 : null,
                zhCountEqEnCount: true,
                limitCallback: (int) {
                  Platform.isAndroid
                      ? VgToastUtils.toast(context, "最多可输入${30}个字")
                      : {};
                },
                onChanged: (value) {
                  setState(() { });
                  // _notifyChange();
                },
              ),
            ),
          ),
          SizedBox(width: 15,),
          Text(
            "${_titleController?.text?.length??0}",
            style: TextStyle(
                fontSize: 10,
                color: color,
            ),
          ),
          Text(
            "/",
            style: TextStyle(
                fontSize: 10,
                color: Color(0XFFB0B3BF)
            ),
          ),
          Text(
            "30",
            style: TextStyle(
                fontSize: 10,
                color: Color(0XFFB0B3BF)
            ),
          ),
        ],
      ),
    );
  }

  ///详细描述
  Widget _toDesWidget() {
    return Container(
      height: 100,
      color: Colors.white,
      padding: EdgeInsets.symmetric(horizontal: 15),
      alignment: Alignment.topLeft,
      child: Container(
        height: 100,
        child: VgTextField(
          controller: _desController,
          keyboardType: TextInputType.text,
          autofocus: false,
          textAlign: TextAlign.left,
          style: TextStyle(
              color: ThemeRepository.getInstance().getCardBgColor_21263C(),
              fontSize: 14),
          decoration: new InputDecoration(
              counterText: "",
              hintText: "可输入详细描述",
              border: InputBorder.none,
              hintStyle: TextStyle(fontSize: 14, color: Color(0XFFB0B3BF))),
          maxLimitLength: Platform.isAndroid ? 200 : null,
          zhCountEqEnCount: true,
          limitCallback: (int) {
            Platform.isAndroid
                ? VgToastUtils.toast(context, "最多可输入${200}个字")
                : {};
          },
          onChanged: (value) {
            // _notifyChange();
            setState(() { });
          },
        ),
      ),
    );
  }

  ///字数提示
  Widget _toDesTextLengthWidget(){
    Color color = Color(0XFFB0B3BF);
    if((_desController?.text?.length??0) > 0){
      if((_desController?.text?.length??0) <= 200){
        color = ThemeRepository.getInstance().getPrimaryColor_1890FF();
      }else{
        color = Color(0XFFF95355);
      }
    }
    return Container(
      height: 20,
      padding: EdgeInsets.only(right: 10),
      alignment: Alignment.centerRight,
      child: Row(
        mainAxisSize: MainAxisSize.min,
        children: [
          Text(
            "${_desController?.text?.length??0}",
            style: TextStyle(
                fontSize: 10,
                color: color,
            ),
          ),
          Text(
            "/",
            style: TextStyle(
                fontSize: 10,
                color: Color(0XFFB0B3BF)
            ),
          ),
          Text(
            "200",
            style: TextStyle(
                fontSize: 10,
                color: Color(0XFFB0B3BF)
            ),
          ),
        ],
      ),
    );
  }

  ///选择图片布局
  Widget _toSelectImageWidget() {
    if(_allList?.length == 1 && (_allList?.elementAt(0)?.isVideo() || _allList?.elementAt(0)?.is3DLink())){
      SmartHomeUploadItemBean itemBean = _allList?.elementAt(0);
      double width = (ScreenUtils.screenW(context) - 30 - 9)/3;
      double height = width;
      String asset = "images/icon_smart_home_video_play.png";
      if (itemBean?.is3DLink() ?? false) {
        asset = "images/icon_smart_home_3d_link.png";
      }
      if(StringUtils.isNotEmpty(itemBean?.getSize()??"")){
        int imageWidth = itemBean.folderWidth;
        int imageHeight = itemBean.folderHeight;
        if(imageHeight > imageWidth){
          height = (width*4)/3;
        }
      }
      return  Expanded(
        child: GestureDetector(
          behavior: HitTestBehavior.opaque,
          onTap: () {
            VgPhotoPreview.listForPage(
              context,
              _uploadList,
              initUrl: itemBean?.getPicOrVideoUrl(),
              urlTrasformFunc: (item) => item?.getPicOrVideoUrl(),
              typeTransformFunc: (item) => PhotoPreviewType.video,
              loadingTransformFunc: (item) => VgPhotoPreview.getImageQualityStr(
                  item.getPicOrVideoUrl(), ImageQualityType.middleDown),
            );


          },
          child: Container(
            width: width,
            height: height,
            margin: EdgeInsets.symmetric(horizontal: 15),
            alignment: Alignment.topLeft,
            child: ClipRRect(
              borderRadius: BorderRadius.circular(4),
              child: Stack(
                alignment: Alignment.center,
                children: <Widget>[
                  VgCacheNetWorkImage(
                    itemBean?.getLocalPicUrl()??"",
                    width: width,
                    height: height,
                    imageQualityType: ImageQualityType.middleDown,
                  ),
                  Image.asset(
                    asset,
                    width: 40,
                  ),
                  Visibility(
                    visible: "03" != widget?.type,
                    child: Positioned(
                      top: 0,
                      right: 0,
                      child: _toDeleteWidget(itemBean),
                    ),
                  ),
                  Visibility(
                    // visible: widget?.type == "03",
                    visible: true,
                    child: Positioned(
                      bottom: 0,
                      child: _toSetCoverWidget(width: width),
                    ),
                  )
                ],
              ),
            ),
          ),
        ),
      );
    }
    return Expanded(
      child: ScrollConfiguration(
        behavior: prefix.MyBehavior(),
        child: _toGridWidget(),
      ),
    );
  }

  Widget _toGridWidget() {
    return GridView.builder(
      padding: EdgeInsets.only(
          left: 15,
          right: 15,
          top: 4,
          bottom: getNavHeightDistance(context)),
      controller: _scrollController,
      itemCount: _allList?.length ?? 0,
      physics: BouncingScrollPhysics(),
      shrinkWrap: true,
      gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
        crossAxisCount: 3,
        mainAxisSpacing: 4,
        crossAxisSpacing: 5,
        childAspectRatio: 1 / 1,
      ),
      itemBuilder: (BuildContext context, int index) {
        return _toGridItemWidget(
            context, _allList?.elementAt(index), index);
      },
    );
  }

  Widget _toGridItemWidget(
      BuildContext context, SmartHomeUploadItemBean itemBean, int index) {
    double width = ScreenUtils.screenW(context) - 30 - 9;
    double height = width;
    String asset = "images/icon_smart_home_video_play.png";
    if (itemBean?.is3DLink() ?? false) {
      asset = "images/icon_smart_home_3d_link.png";
    }
    if(StringUtils.isNotEmpty(itemBean?.getSize()??"")){
      int imageWidth = itemBean.folderWidth;
      int imageHeight = itemBean.folderHeight;
      if(imageHeight > imageWidth){
        height = (width*4)/3;
      }
    }
    print("height:" + height.toString() + ",width:" + width.toString());
    if (itemBean?.isDefault() ?? false) {
      return GestureDetector(
        behavior: HitTestBehavior.opaque,
        onTap: throttle(() async {
          _selectImage();
          await Future.delayed(Duration(milliseconds: 2000));
        }),
        child: Container(
          width: width,
          height: width,
          decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(4), color: Color(0XFFF6F7F9)),
          alignment: Alignment.center,
          child: Image.asset(
            "images/icon_smart_home_add_img.png",
            width: 40,
          ),
        ),
      );
    }
    return GestureDetector(
      behavior: HitTestBehavior.opaque,
      onTap: () {
        if(itemBean?.is3DLink()??false){
          SmartHome3DLinkDemoPage.navigatorPush(context, _linkUrl);
        }else{
          VgPhotoPreview.listForPage(
            context,
            _uploadList,
            initUrl: itemBean?.getPicOrVideoUrl(),
            urlTrasformFunc: (item) => item?.getPicOrVideoUrl(),
            typeTransformFunc: (item) => (item?.isImage())?PhotoPreviewType.image:((item?.isVideo())?PhotoPreviewType.video:PhotoPreviewType.unknow),
            loadingTransformFunc: (item) => VgPhotoPreview.getImageQualityStr(
                item.getPicOrVideoUrl(), ImageQualityType.middleDown),
          );
        }

      },
      child: ClipRRect(
        borderRadius: BorderRadius.circular(4),
        child: Stack(
          alignment: Alignment.center,
          children: <Widget>[
            VgCacheNetWorkImage(
              itemBean?.getLocalPicUrl() ?? "",
              width: width,
              height: height,
              imageQualityType: ImageQualityType.middleDown,
            ),
            Visibility(
              visible: (itemBean?.isVideo() ?? false) ||
                  (itemBean?.is3DLink() ?? false),
              child: Image.asset(
                asset,
                width: 40,
              ),
            ),
            Visibility(
              visible: widget?.type == "01" &&
                  _uploadList.length > 1 &&
                  _coverIndex != null &&
                  (_uploadList?.elementAt(_coverIndex)?.getLocalPicUrl() ==
                      (itemBean?.getLocalPicUrl() ?? "")),
              child: Positioned(
                top: 6,
                left: 6.5,
                child: Container(
                  height: 13,
                  width: 26,
                  alignment: Alignment.center,
                  decoration: BoxDecoration(
                      borderRadius: BorderRadius.circular(1),
                      color: Color(0XFFFFB714)),
                  child: Text(
                    "封面",
                    style: TextStyle(
                      fontSize: 9,
                      color:
                      ThemeRepository.getInstance().getCardBgColor_21263C(),
                    ),
                  ),
                ),
              ),
            ),
            Visibility(
              visible: "03" != widget?.type,
              child: Positioned(
                top: 0,
                right: 0,
                child: _toDeleteWidget(itemBean),
              ),
            ),
            Visibility(
              visible: widget?.type == "01" && _uploadList.length > 1 && index == 0,
              child: Align(
                alignment: Alignment.bottomCenter,
                child: _toSetCoverWidget(),
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _toSetCoverWidget({double width}){
    return GestureDetector(
      behavior: HitTestBehavior.opaque,
      onTap: () async {
        if ("01" == widget.type) {
          int coverIndex =
          await SmartHomePublishSetImageCoverPage.navigatorPush(
              context, _uploadList, _coverIndex);
          if (coverIndex != null) {
            setState(() {
              _coverIndex = coverIndex;
            });
          }
        }else if("02" == widget.type){
          SmartHomeUploadItemBean videoInfo = await SmartHomePublishSetVideoCoverPage.navigatorPush(context, _uploadList.elementAt(0));
          if(videoInfo == null){
            return;
          }
          print("videoInfo1:${videoInfo.getLocalPicUrl()}");
          setState(() {
            _uploadList[0] = videoInfo;
            _allList.clear();
            _allList.addAll(_uploadList);
          });
        } else {
          String coverPath = await MatisseUtil.clipOneImage(context, scaleX: 3, scaleY: 4,
              onRequestPermission: (msg)async{
                bool result =
                await CommonConfirmCancelDialog.navigatorPushDialog(context,
                  title: "提示",
                  content: msg,
                  cancelText: "取消",
                  confirmText: "去授权",
                  confirmBgColor: ThemeRepository.getInstance().getPrimaryColor_1890FF(),
                  cancelBgColor: Color(0xFFF6F7F9),
                  titleColor: ThemeRepository.getInstance().getCardBgColor_21263C(),
                  contentColor: ThemeRepository.getInstance().getCardBgColor_21263C(),
                  widgetBgColor: Colors.white,
                );
                if (result ?? false) {
                  PermissionUtil.openAppSettings();
                }
              });
          if(coverPath == null){
            return;
          }
          if (StringUtils.isNotEmpty(coverPath)) {
            setState(() {
              List<String> resultList = new List();
              resultList.add(coverPath);
              _uploadList.clear();
              _doHandleData(resultList);
            });
          }
        }
      },
      child: Container(
        height: 32,
        width: width??double.maxFinite,
        alignment: Alignment.center,
        decoration: BoxDecoration(
            borderRadius: BorderRadius.only(
                bottomLeft: Radius.circular(4),
                bottomRight: Radius.circular(4)),
            color: Color(0X80000000)),
        child: Text(
          "选封面",
          style: TextStyle(
            fontSize: 12,
            fontWeight: FontWeight.w600,
            color: Colors.white,
          ),
        ),
      ),
    );
  }

  _toDeleteWidget(SmartHomeUploadItemBean itemBean) {
    return GestureDetector(
      behavior: HitTestBehavior.opaque,
      onTap: () {
        setState(() {
          if ("01" == widget?.type) {

            if(_coverIndex != null &&
                (_uploadList?.elementAt(_coverIndex)?.getLocalPicUrl() ==
                    (itemBean?.getLocalPicUrl() ?? ""))){
              //当前删除的是封面，
              _coverIndex = 0;
              _uploadList.remove(itemBean);
            }else{
              //当前删除的不是封面
              SmartHomeUploadItemBean covertItem = _uploadList?.elementAt(_coverIndex);
              _uploadList.remove(itemBean);
              _coverIndex = _uploadList.indexOf(covertItem);
            }
            //图片
            if (_uploadList.length < 35) {
              _allList.clear();
              _allList.addAll(_uploadList);
              _allList.add(_defaultItem);
            }
          } else if ("02" == widget?.type) {
            _uploadList.remove(itemBean);
            _allList.clear();
            _allList.add(_defaultItem);
          } else {
            _uploadList.remove(itemBean);
            _allList.clear();
            _allList.add(_defaultItem);
          }
          _picCount = _uploadList.length;
        });
      },
      child: Container(
        height: 35,
        width: 35,
        alignment: Alignment.topRight,
        padding: EdgeInsets.only(top: 6, right: 6),
        child: Image.asset(
          "images/icon_smart_home_delete_img.png",
          width: 15,
        ),
      ),
    );
  }

  ///选择bgm
  Widget _toSelectBgmWidget(){
    return Visibility(
      visible: widget?.type == "01",
      child: GestureDetector(
        behavior: HitTestBehavior.opaque,
        onTap: ()async{
          if(_musicList.isEmpty){
            _musicViewModel.getBgByHsn(context, "", (musicList) async {
              _musicList.addAll(musicList);
              MusicListBean musicListBean = await SetSmartHomeFolderBgmDialog.navigatorPushDialog(context, _musicList, null, _musicInfo?.id);
              if(musicListBean != null){
                setState(() {
                  _musicInfo = musicListBean;
                });
              }

            });
          }else{
            MusicListBean musicListBean = await SetSmartHomeFolderBgmDialog.navigatorPushDialog(context, _musicList, null, _musicInfo?.id);
            if(musicListBean != null){
              setState(() {
                _musicInfo = musicListBean;
              });
            }
          }
        },
        child: Container(
          height: 50 + ScreenUtils.getBottomBarH(context),
          padding: EdgeInsets.only(left: 15, right: 15, bottom: ScreenUtils.getBottomBarH(context)),
          alignment: Alignment.centerLeft,
          decoration: BoxDecoration(
              color: Colors.white,
              boxShadow: [ BoxShadow(
                  color: Color(0xff000000).withOpacity(0.06),
                  offset: Offset(0, -2),
                  blurRadius: 20
              )]
          ),
          child: Row(
            children: [
              Container(
                width: 38,
                height: 38,
                alignment: Alignment.center,
                child: Opacity(
                  opacity: (_musicInfo == null)?0.5:1,
                  child: Image.asset(
                    "images/icon_smart_home_bgm.png",
                    width: 32,
                    height: 32,
                  ),
                ),
              ),
              SizedBox(width: 8,),
              Expanded(
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      _musicInfo?.mname??"背景音乐",
                      style: TextStyle(
                        fontSize: 15,
                        color: ThemeRepository.getInstance().getCardBgColor_21263C(),
                      ),
                    ),
                    Visibility(visible: _musicInfo != null,child: SizedBox(height: 1,)),
                    Visibility(
                        visible: _musicInfo != null,
                        child: Text(
                          _musicInfo?.mtime??"",
                          style: TextStyle(
                              fontSize: 11,
                              color: Color(0XFF8B93A5)
                          ),
                        )
                    ),
                  ],
                ),
              ),
              Spacer(),
              Visibility(
                  visible: _musicInfo == null,
                  child: Text(
                    "去选择",
                    style: TextStyle(
                        fontSize: 12,
                        color: Color(0XFF8B93A5)
                    ),
                  )
              ),
              SizedBox(width: 8,),
              Image.asset(
                "images/icon_arrow_right_grey.png",
                width: 6,
                color: Color(0XFF8B93A5),
              ),
            ],
          ),
        ),
      ),
    );
  }

  /// 函数节流
  ///
  /// [func]: 要执行的方法
  Function throttle(
      Future Function() func,
      ) {
    if (func == null) {
      return func;
    }
    bool enable = true;
    Function target = () {
      if (enable == true) {
        enable = false;
        func().then((_) {
          enable = true;
        });
      }
    };
    return target;
  }

  void _selectImage() async {
    List<String> resultList;
    if ("01" == widget?.type) {
      //图片
      resultList = await MatisseUtil.selectPhoto(
          context: context,
          maxSize: (35 - (_uploadList?.length??0)),
          maxAutoFinish: false,
          imageRadioMaxLimit: 3,
          imageRadioMinLimit: 0.3,
          onRequestPermission: (msg)async{
            bool result =
            await CommonConfirmCancelDialog.navigatorPushDialog(context,
              title: "提示",
              content: msg,
              cancelText: "取消",
              confirmText: "去授权",
              confirmBgColor: ThemeRepository.getInstance().getPrimaryColor_1890FF(),
              cancelBgColor: Color(0xFFF6F7F9),
              titleColor: ThemeRepository.getInstance().getCardBgColor_21263C(),
              contentColor: ThemeRepository.getInstance().getCardBgColor_21263C(),
              widgetBgColor: Colors.white,
            );
            if (result ?? false) {
              PermissionUtil.openAppSettings();
            }
          }
      );
    } else if ("02" == widget?.type) {
      resultList = await MatisseUtil.selectVideo(
          context: context, maxSize: 1, maxAutoFinish: false,
          onRequestPermission: (msg)async{
            bool result =
            await CommonConfirmCancelDialog.navigatorPushDialog(context,
              title: "提示",
              content: msg,
              cancelText: "取消",
              confirmText: "去授权",
              confirmBgColor: ThemeRepository.getInstance().getPrimaryColor_1890FF(),
              cancelBgColor: Color(0xFFF6F7F9),
              titleColor: ThemeRepository.getInstance().getCardBgColor_21263C(),
              contentColor: ThemeRepository.getInstance().getCardBgColor_21263C(),
              widgetBgColor: Colors.white,
            );
            if (result ?? false) {
              PermissionUtil.openAppSettings();
            }
          });
    }
    _doHandleData(resultList);
  }

  void _doHandleData(List<String> resultList) {
    if (resultList == null || resultList.isEmpty) {
      return;
    }
    List<SmartHomeUploadItemBean> selectList = List();
    Map<String, ImageInfo> _imageInfoMap = new Map();
    //获取选择的图片或者视频
    String localUrl = resultList[0];
    if (StringUtils.isEmpty(localUrl)) {
      return;
    }
    if (resultList.length == 1 && MatisseUtil.isVideo(localUrl)) {
      //处理视频逻辑
      loading(true, msg: "视频处理中");
      handleVideo(localUrl, selectList);
    } else {
      loading(true, msg: "图片处理中");
      int computeCount = 0;
      resultList.forEach((element) {
        FileImage image = FileImage(File(element));
        image.resolve(new ImageConfiguration()).addListener(
            new ImageStreamListener((ImageInfo info, bool _) async {
              _imageInfoMap[element] = info;
              computeCount++;
              if (computeCount == resultList.length) {
                loading(false);
                resultList.forEach((element) {
                  selectList.add(SmartHomeUploadItemBean(
                    linkUrl: _linkUrl ?? "",
                    localUrl: element,
                    type: widget?.type,
                    // scid: _currentColumn?.getScid() ?? "",
                    scid: "",
                    folderWidth: _imageInfoMap[element].image.width,
                    folderHeight: _imageInfoMap[element].image.height,
                  ));
                });
                setState(() {
                  _uploadList.addAll(selectList);
                  if (_uploadList.length < 35) {
                    _allList.clear();
                    _allList.addAll(_uploadList);
                    if (widget?.type == "01") {
                      _allList.add(_defaultItem);
                    }
                  } else {
                    _allList.clear();
                    _allList.addAll(_uploadList);
                  }
                  if (_coverIndex == null) {
                    _coverIndex = 0;
                  }
                  _picCount = _uploadList.length;
                });
                Future.delayed(Duration(milliseconds: 300), () {
                  _scrollController.jumpTo(_scrollController.position.maxScrollExtent);
                });
              }
            }));
      });
    }
  }

  ///处理视频的逻辑
  void handleVideo(
      String localUrl, List<SmartHomeUploadItemBean> selectList) async {
    //视频
    print("handleVideo:" + _currentColumn?.getScid() ?? "");
    SmartHomeUploadItemBean item = SmartHomeUploadItemBean(
      localUrl: localUrl,
      type: "02",
      // scid: _currentColumn?.getScid() ?? "",
      scid: "",
    );
    File file = File(item.localUrl);
    Directory rootPath = await getTemporaryDirectory();
    Directory tempDirectory = new Directory('${rootPath.path}/imageTemp');
    if (!tempDirectory.existsSync()) {
      tempDirectory.createSync();
    }

    String tmpVideoCover = await VideoThumbnail.thumbnailFile(
      video: item.localUrl,
      thumbnailPath: tempDirectory?.path,
      imageFormat: ImageFormat.JPEG,
      maxWidth: 1920,
      quality: 100,
    );
    item.videoLocalCover = tmpVideoCover;

    _videoHandleController = VideoPlayerController.file(file);
    await _videoHandleController.initialize();
    item.videoDuration = _videoHandleController?.value?.duration?.inSeconds;
    item.folderWidth = _videoHandleController?.value?.size?.width?.floor();
    item.folderHeight = _videoHandleController?.value?.size?.height?.floor();
    item.folderStorage = file.lengthSync();
    selectList.add(item);
    _videoHandleController?.dispose();
    loading(false);
    setState(() {
      _uploadList.addAll(selectList);
      if (_uploadList.length < 35) {
        _allList.clear();
        _allList.addAll(_uploadList);
      } else {
        _allList.clear();
        _allList.addAll(_uploadList);
      }
    });
  }
}
